package com.indeep.user.demo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class StudentProxyHandler implements InvocationHandler {
    private final Student student;
    private final SubjectListener listener;
    private final ExecutorService executorService;
    
    public StudentProxyHandler(Student student, SubjectListener listener) {
        this.student = student;
        this.listener = listener;
        this.executorService = Executors.newFixedThreadPool(5); // 创建一个具有5个线程的线程池
    }
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        listener.onMethodCalled(method.getName(), args); // 通知监听者方法被调用
        return executorService.submit(() -> {
            try {
                return method.invoke(student, args);
            } catch (Exception e) {
                throw new RuntimeException("Error invoking method " + method.getName(), e);
            }
        }).get(); // 同步等待线程池任务完成
    }
}